﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.ComponentModel;

namespace ArbolandiaBL
{

    public class UIShoppingCart
    {
        private ArbolandiaDBDataContext _db;

        public UIShoppingCart()
        {
            _db = new ArbolandiaDBDataContext();
        }

        public void SaveShopping(Orders saveobj, Customer cus, CustomerAddress add)
        {
            try
            {
                _db.Orders.InsertOnSubmit(saveobj);
                _db.Customer.InsertOnSubmit(cus);
                _db.CustomerAddress.InsertOnSubmit(add);
                _db.SubmitChanges();
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void ChangeStatus(Guid guidCustomer, short status)
        {
            try
            {
                var query = _db.Orders.Where(w => w.CustomerGuid == guidCustomer);
                if (query.Count() > 0)
                {
                    var estatus = Utilities.STATUS_XX;
                    if (status == 1) { estatus = Utilities.STATUS_1; }
                    else if (status == 2) { estatus = Utilities.STATUS_2; }
                    else if (status == 3) { estatus = Utilities.STATUS_3; }
                    else if (status == 4) { estatus = Utilities.STATUS_4; }
                    else { estatus = Utilities.STATUS_XX; }
                    query.First().iEstaus = status;
                    query.First().Estaus = estatus;
                    _db.SubmitChanges();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void SendEmail(Guid guidCustomer, Guid guidOrder)
        {
            var customer = GetCustomer(guidCustomer);
            var order = GetOrder(guidOrder);
            var address = GetAddress(guidCustomer);

            string emailTo = System.Configuration.ConfigurationManager.AppSettings["emailTo"];
            string emailFrom = System.Configuration.ConfigurationManager.AppSettings["emailFrom"];
            var path = HttpContext.Current.Server.MapPath("~/templates/emailtemplate.htm");
            string bodyEmail = "";
            bodyEmail = bodyEmail = File.ReadAllText(path);
            var sb = new StringBuilder();
            string sysdate = order.SystemDate.HasValue ? order.SystemDate.Value.ToString("s") : DateTime.Now.ToString("s");
            sb.Append("<p> Fecha:" + sysdate + " </p>");
            sb.Append("<p> Nombre Completo:" + customer.Names + " " + customer.LastNames + " </p>");
            sb.Append("<p> Telefono :" + customer.MobilePhoneNumber + " </p>");
            sb.Append("<p> Email :" + customer.Email + " </p>");
            sb.Append("<p> Direccion :" + address.FullAddress + " " + address.City + " " + address.State + " " + address.ZipCode + " </p>");
            sb.Append("<p style='font-weight: bold;'> Detalle Compra : </p>");
            var ordersDetail = Utilities.DesSerializeJson<List<Utilities.OrderJson>>(order.OrderFullJson);
            foreach (var item in ordersDetail)
            {
                string code = CompiledQuerys.GetProductCode(_db, item.productId, item.productDetailId);
                sb.Append("<br/><p style='font-weight: bold;'> Codigo Producto :" + code + " </p>");
                sb.Append("<p> Cantidad :" + item.quantity.ToString() + " </p>");
                sb.Append("<p> Importe :" + item.amount.ToString() + " </p>");
            }
            sb.Append("<br/><p> Subtotal :" + order.SubTotal.ToString() + " </p>");
            sb.Append("<p> Otros :" + order.Otros.ToString() + " </p>");
            sb.Append("<p> IVA :" + order.Iva.ToString() + " </p>");
            sb.Append("<p style='font-weight: bold; color:blue;'> Total :" + order.Total.ToString() + " </p><br/>");
            bodyEmail = bodyEmail.Replace("@@Estatus", order.Estaus);
            bodyEmail = bodyEmail.Replace("@@DetallePedido", sb.ToString());

            SmtpClient mailClient = new SmtpClient();
            mailClient.EnableSsl = false;
            MailAddressCollection addCollection = new MailAddressCollection();
            addCollection.Add(emailTo);
            MailMessage message = new MailMessage(emailFrom, addCollection.ToString());
            message.Subject = "Detalles Compra Arbolandia.com";
            message.Body = bodyEmail;
            message.IsBodyHtml = true;
            mailClient.SendAsync(message, emailTo + " Customer: " + guidCustomer.ToString() + " Order:" + order.OrderFullJson);
            mailClient.SendCompleted += new SendCompletedEventHandler(SendEmailCompleted);
        }
        internal void SendEmailCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                var sysLog = new SystemLog();
                String token = (string)e.UserState;
                sysLog.Data = token;
                sysLog.SystemDate = DateTime.Now;
                if (e.Cancelled)
                {
                    sysLog.ErrorMessage = "Cancelado";
                }
                if (e.Error != null)
                {
                    sysLog.ErrorMessage = e.Error.Message;
                }
                else
                {
                    sysLog.ErrorMessage = "";
                }
                _db.SystemLog.InsertOnSubmit(sysLog);
                _db.SubmitChanges();
            }
            catch (Exception)
            {

                throw;
            }

        }
        public Customer GetCustomer(Guid guidCustomer)
        {
            var res = new Customer();
            var query = _db.Customer.Where(w => w.CustomerGuid == guidCustomer);
            res = query.Count() > 0 ? query.First() : new Customer();
            return res;
        }
        public Orders GetOrder(Guid orderGuid)
        {
            var res = new Orders();
            var query = _db.Orders.Where(w => w.OrderGuid == orderGuid);
            res = query.Count() > 0 ? query.First() : new Orders();
            return res;

        }
        public CustomerAddress GetAddress(Guid guidCustomer)
        {
            var res = new CustomerAddress();
            var query = _db.CustomerAddress.Where(w => w.CustomerGuid == guidCustomer);
            res = query.Count() > 0 ? query.First() : new CustomerAddress();
            return res;

        }

    }
}
